package org.thirdHero.admin.annotation.support;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.thirdHero.admin.annotation.LoginAdmin;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.thirdHero.core.enums.ResultEnum;
import org.thirdHero.core.exception.TokenErrorException;
import org.thirdHero.core.token.UserToken;
import org.thirdHero.core.token.UserTokenManager;
import org.thirdHero.db.domain.SysUser;

import javax.annotation.Resource;

@Component
public class LoginAdminHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    private final static Logger logger = LoggerFactory.getLogger(LoginAdminHandlerMethodArgumentResolver.class);

    public static final String LOGIN_TOKEN_KEY = "X-Token";

    @Resource
    private UserTokenManager userTokenManager;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(SysUser.class)&&parameter.hasParameterAnnotation(LoginAdmin.class);
    }

    /**
     * 获取当前登录的token值
     * @param parameter
     * @param container
     * @param request
     * @param factory
     * @return
     * @throws Exception
     */
    @Override
    public SysUser resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                   NativeWebRequest request, WebDataBinderFactory factory) throws Exception {

        String token = request.getHeader(LOGIN_TOKEN_KEY);
        if(token == null || token.isEmpty()){
            throw  new TokenErrorException(ResultEnum.ERROR_TOKEN_EMPTY);
        }
        Object sessionUser = userTokenManager.getSessionUser(token);
        if(sessionUser==null){
            throw  new TokenErrorException(ResultEnum.ERROR_TOKEN_EMPTY);
        }
        if(sessionUser  instanceof UserToken){
            throw  new TokenErrorException(ResultEnum.ERROR_SESSION_USER);
        }
        //转换为了防止dev-tools导致运行环境不一致从而引起的类型转换的问题
        return JSON.parseObject(JSON.toJSON(sessionUser).toString(),SysUser.class);
    }
}
